/**
 * LoginController
 *
 * @description :: Server-side logic for managing Logins
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */
var uuid = require("node-uuid");
var patterns = /^[a-zA-Z]\w+$/


module.exports = {

	login: function(req, res){
	
		var params = req.params.all();

		var username = params.username;
		var password = params.password;



		if(!username || !patterns.test(username)) {

			return res.json({
				code: -1,
				message: "用户名错误"
			});

		}
		
		if(!password || !patterns.test(password)) {

			return res.json({
				code: -1,
				message: "密码错误"
			});

		}


		User.findOne({
			username:username
		}).exec(function(err, user){


			if(err || user==null) {

				return res.json({
					code: -1,
					message: "用户名错误"
				});

			};



			HashService.hash(password, user.salt, function(err, data){

				if(user.password != data.toString()) {


					return res.json({
						code: -1,
						message: "密码错误"
					});

				};

				var newToken = uuid.v4();

				User.update({id:user.id},{token:newToken}).exec(function(err, _user){

					if(err) {
						return res.json({
							code: -1,
							message: "登录失败"
						});
					}else {
					
						return res.json({
							code: 0,
							id: user.id,
							username: username,
							token: newToken
						});


					}

					
				});


			})


		})


	}


};

